<?php

namespace app\models;

use Yii;
use yii\base\BaseObject;
use yii\web\IdentityInterface;

class User extends BaseObject implements IdentityInterface
{
    public $id;
    public $username;
    public $password;
    public $rank;
    public $authKey;
    public $accessToken;

    private static $users = [];

    /**
     * @param int|string $id
     *
     * @return \app\models\User|\yii\web\IdentityInterface|null
     * @author sally
     * @date   2020-05-10
     */
    public static function findIdentity($id)
    {
        $manager = \app\modules\setting\models\User::findOne(['username' => $id]);

        if (empty($manager->user_id) || empty($manager->username)) {
            return NULL;
        }

        $user = [
            'id' => $manager->user_id,
            'username' => $manager->username,
            'accessToken' => '103-token',
        ];

        return new static($user);
    }

    /**
     * @inheritdoc
     */
    public static function findIdentityByAccessToken($token, $type = null)
    {
        foreach (self::$users as $user) {
            if ($user['accessToken'] === $token) {
                return new static($user);
            }
        }

        return null;
    }

    /**
     * Finds user by username
     *
     * @param string $username
     * @return static|null
     */
    public static function findByUsername($username)
    {
        foreach (self::$users as $user) {
            if (strcasecmp($user['username'], $username) === 0) {
                return new static($user);
            }
        }

        return null;
    }

    /**
     * @inheritdoc
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * @inheritdoc
     */
    public function getAuthKey()
    {
        return $this->authKey;
    }

    /**
     * @inheritdoc
     */
    public function validateAuthKey($authKey)
    {
        return $this->authKey === $authKey;
    }

    /**
     * Validates password
     *
     * @param string $password password to validate
     * @return bool if password provided is valid for current user
     */
    public function validatePassword($password)
    {
        return $password === Yii::$app->params['admin_password'];
    }
}
